<template>
  <div class="search-college">
    <div class="header">
      <img @click="goBack" class="back-arrow" :src="backArrow" alt="" />
      <SchoolSearchBox @updateData="handleUpdateData" />
    </div>
    <div class="school-info">
      <div class="top">
        <div class="left">
          <span v-if="showTest">-</span>
          <img class="school-logo" :src="mySchoolInfo.icon" alt="" />
        </div>
        <div class="right">
          <div class="school-name">
            <div class="name">{{ mySchoolInfo.name }}</div>
            <template v-if="mySchoolInfo?.dualClassName != ''">
              <div
                class="label"
                v-for="(item, index) in mySchoolInfo?.dualClassName?.split(',')"
                :key="index"
              >
                {{ item }}
              </div>
            </template>
          </div>
          <div class="tags">
            {{ mySchoolInfo.collegeType }}
            <span v-if="mySchoolInfo.natureName">/</span>
            {{ mySchoolInfo.natureName }}
            <span v-if="mySchoolInfo.tagName">/</span>
            {{ mySchoolInfo.tagName }}
          </div>
        </div>
        <div class="star-box">
          <img
            class="star"
            :src="isCollect == 1 ? noBorderYellowStar : blueStarPlus"
            alt=""
            @click="handleClickStar"
          />
        </div>
      </div>
      <div class="middle">
        <div class="left">
          <div
            class="left-item"
            v-for="(item, index) in basicInfo"
            :key="index"
          >
            <div class="logo">
              <img :src="item.icon" alt="" />
            </div>
            <div class="info">
              <div class="title">{{ item.title }}</div>
              <div>{{ item.value }}</div>
            </div>
          </div>
        </div>
        <div class="right">
          <div
            class="right-item"
            v-for="(item, index) in contactInfo"
            :key="index"
            @click="handleOpenWebsite(item)"
          >
            <img :src="item.icon" alt="" />
            <div>
              {{ item.title }}：<span
                :class="['value', item.isSite ? 'site' : '']"
                >{{ item.value }}</span
              >
            </div>
          </div>
        </div>
      </div>
      <div class="main">
        <div class="filter-box">
          <div
            :class="activeTabIndex == index ? 'active-tab' : 'tab'"
            v-for="(item, index) in filterTabList"
            :key="index"
            @click="changeActiveTab(item, index)"
          >
            {{ item.title }}
          </div>
        </div>
        <div class="container">
          <!-- <keep-alive>
            <component
              :is="activeComponent"
              :schoolInfoParams="schoolInfoParams"
              :schoolIntroParams="schoolIntroParams"
              :schoolPicParams="schoolPicParams"
              :currentCollegeId="currentCollegeId"
              :localRegionId="localRegionId"
              :schoolFilterParams="campusOptions"
            />
          </keep-alive> -->
          <SchoolInfo
            v-if="activeTabIndex == 0"
            :schoolInfoParams="schoolInfoParams"
          />
          <SchoolIntro
            v-if="activeTabIndex == 1"
            :schoolIntroParams="schoolIntroParams"
          />
          <SchoolPic
            v-if="activeTabIndex == 2"
            :schoolPicParams="schoolPicParams"
          />
          <SchoolMajor
            v-if="activeTabIndex == 3"
            :currentCollegeId="currentCollegeId"
          />
          <SchoolScore
            v-if="activeTabIndex == 4"
            :schoolFilterParams="campusOptions"
            :localRegionId="localRegionId"
          />
          <SchoolPlan
            v-if="activeTabIndex == 5"
            :schoolFilterParams="campusOptions"
            :localRegionId="localRegionId"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  onActivated,
  onDeactivated,
  shallowRef,
  defineAsyncComponent,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';

import {
  getCollegeDetails,
  campusCollect,
  campusIsCollect,
  getZtjUserInfo,
  getCollegeFilter,
} from '@/api/collegeSearch';
import { onBackPressed, onOpenWebsitePressed } from '@/utils/androidFn.js';

import backArrow from '@/assets/images/back_arrow.png';
import jxsj from '@/assets/images/jxsj.png';
import zdmj from '@/assets/images/zdmj.png';
import zgbm from '@/assets/images/zgbm.png';
import xxwz from '@/assets/images/xxwz.png';
import xxgw from '@/assets/images/xxgw.png';
import zsdh from '@/assets/images/zsdh.png';
import airplane from '@/assets/images/airplane.png';
import noBorderYellowStar from '@/assets/images/noBorderYellowStar.png';
import blueStarPlus from '@/assets/images/blueStarPlus.png';

const SchoolSearchBox = defineAsyncComponent(() =>
  import('@/components/SchoolSearchBox.vue')
);
const SchoolInfo = defineAsyncComponent(() =>
  import('./components/SchoolInfo.vue')
);
const SchoolIntro = defineAsyncComponent(() =>
  import('./components/SchoolIntro.vue')
);
const SchoolPic = defineAsyncComponent(() =>
  import('./components/SchoolPic.vue')
);
const SchoolMajor = defineAsyncComponent(() =>
  import('./components/SchoolMajor.vue')
);
const SchoolScore = defineAsyncComponent(() =>
  import('./components/SchoolScore.vue')
);
const SchoolPlan = defineAsyncComponent(() =>
  import('./components/SchoolPlan.vue')
);

const router = useRouter();
// 获取当前的路由对象
const route = useRoute();

const isCollect = ref(false);
const campusIsCollectFn = async () => {
  const params = {
    dataId: currentCollegeId.value,
    dataType: 13,
  };
  const res = await campusIsCollect(params);
  if (res.code == 200) {
    isCollect.value = res.data;
  }
};

const handleClickStar = async () => {
  const params = {
    dataId: currentCollegeId.value,
    dataType: 13,
    action: isCollect.value ? 0 : 1, // 1:收藏 0:取消收藏
  };
  const res = await campusCollect(params);
  if (res.code == 200) {
    showToast(params.action == 1 ? '收藏成功！' : '已取消收藏');
    isCollect.value = params.action == 1 ? true : false;
  }
};

const goBack = () => {
  if (route.query?.fromType == 'android') {
    onBackPressed(router);
  } else if (route.query?.rebackUrl) {
    window.location.replace(route.query.rebackUrl);
  } else {
    if (localStorage.getItem('isSchoolDetail') == '1') {
      console.log('回到安卓');
      onBackPressed(router);
      localStorage.removeItem('isSchoolDetail');
    } else {
      router.go(-1);
    }
  }
};

const getCollegeDetailsFn = async () => {
  const params = {
    collegeId: currentCollegeId.value,
  };
  const res = await getCollegeDetails(params);
  if (res.code == 200) {
    mySchoolInfo.value = res.data;
    basicInfo.value[0].value = res.data.detail.schoolCreateDate; // 建校时间
    basicInfo.value[1].value = res.data.detail.area + '亩'; // 占地面积
    basicInfo.value[2].value = res.data.detail.belong; // 主管部门
    contactInfo.value[0].value =
      res.data.provinceName + '·' + res.data.cityName;
    contactInfo.value[1].value = res.data.detail.schoolSite;
    contactInfo.value[2].value = res.data.detail.phone.split(',')[0];
    contactInfo.value[3].value = res.data.detail.site;
    schoolPicParams.value = res.data.detail.images;
    schoolIntroParams.value = res.data.detail.content;
    schoolInfoParams.value = res.data.detail;
  }
};

const currentCollegeId = ref('');
const mySchoolInfo = ref(''); // 学校信息
const basicInfo = ref([
  {
    title: '建校时间',
    icon: jxsj,
    value: '111',
  },
  {
    title: '占地面积',
    icon: zdmj,
    value: '111',
  },
  {
    title: '主管部门',
    icon: zgbm,
    value: '111',
  },
]);
const contactInfo = ref([
  {
    title: '学校位置',
    icon: xxwz,
    value: '',
  },
  {
    title: '学校官网',
    icon: xxgw,
    value: '',
    isSite: true,
  },
  {
    title: '招生电话',
    icon: zsdh,
    value: '',
  },
  {
    title: '招生官网',
    icon: airplane,
    value: '',
    isSite: true,
  },
]);
const filterTabList = ref([
  {
    title: '学校概况',
    component: SchoolInfo,
  },
  {
    title: '学校介绍',
    component: SchoolIntro,
  },
  {
    title: '校园风光',
    component: SchoolPic,
  },
  {
    title: '开设专业',
    component: SchoolMajor,
  },
  {
    title: '·历年分数',
    component: SchoolScore,
  },
  {
    title: '·招生计划',
    component: SchoolPlan,
  },
]);
const activeTabIndex = ref(0);
let activeComponent = shallowRef(SchoolInfo);
const changeActiveTab = (item, index) => {
  activeTabIndex.value = index;
  activeComponent.value = item.component;
};
// 这是不同组件需要的参数
const schoolInfoParams = ref(null);
const schoolIntroParams = ref(null);
const schoolPicParams = ref(null);
const schoolMajorParams = ref(null);
const handleUpdateData = () => {
  activeTabIndex.value = -1;
  //filterTabList要进行初始化
  filterTabList.value = [
    {
      title: '学校概况',
      component: SchoolInfo,
    },
    {
      title: '学校介绍',
      component: SchoolIntro,
    },
    {
      title: '校园风光',
      component: SchoolPic,
    },
    {
      title: '开设专业',
      component: SchoolMajor,
    },
    {
      title: '·历年分数',
      component: SchoolScore,
    },
    {
      title: '·招生计划',
      component: SchoolPlan,
    },
  ];
  // 刷新页面
  setTimeout(() => {
    activeTabIndex.value = 0;
    currentCollegeId.value = route.query.dataId;
    activeComponent.value = filterTabList.value[0].component;
    getCollegeDetailsFn();
    campusIsCollectFn();
    getCollegeFilterFn();
  }, 500);
};
const handleOpenWebsite = (item) => {
  if (item.title == '学校官网' || item.title == '招生官网') {
    if (!item.value) return;
    // 清理 URL，移除 @ 符号等不必要的字符
    let cleanUrl = item.value.trim();
    // 确保 URL 有协议
    if (!cleanUrl.startsWith('http://') && !cleanUrl.startsWith('https://')) {
      cleanUrl = 'https://' + cleanUrl;
    }

    onOpenWebsitePressed(cleanUrl); // TODO:还要和安卓对接具体情况
    // router.push({
    //   name: 'IframeSitePage',
    //   query: {
    //     url: cleanUrl,
    //     name: mySchoolInfo.value.name + item.title,
    //   },
    // });
  }
};

const localRegionId = ref('');
const localRegionName = ref('');
const getZtjUserInfoFn = async () => {
  const res = await getZtjUserInfo({});
  if (res.code == 200) {
    localRegionId.value = res.data.regionId || '440000';
    localRegionName.value = res.data.regionName || '广东';
    //给filterTabList的最后两个title添加拼接localRegionName
    if (filterTabList.value.length > 2) {
      filterTabList.value[filterTabList.value.length - 2].title =
        localRegionName.value +
        filterTabList.value[filterTabList.value.length - 2].title;
      filterTabList.value[filterTabList.value.length - 1].title =
        localRegionName.value +
        filterTabList.value[filterTabList.value.length - 1].title;
    }
    // 获取到 localRegionId 后，立即执行 getCollegeFilterFn
    await getCollegeFilterFn();
  }
};
const campusOptions = ref([]);
const getCollegeFilterFn = async () => {
  const params = {
    localRegionId: localRegionId.value,
    useCase: '10',
  };
  const res = await getCollegeFilter(params);
  if (res.code == 200) {
    if (res.data.length > 0) {
      campusOptions.value = res.data;
    } else {
      //filterTabList删除最后两项
      if (filterTabList.value.length > 2) {
        filterTabList.value.splice(-2);
      }
    }
  }
};

const showTest = ref(false);
// 如果域名包含test，则显示测试文字
if (
  window.location.href.indexOf('test') !== -1 ||
  window.location.href.indexOf('localhost') !== -1
) {
  showTest.value = true;
}

onMounted(() => {
  currentCollegeId.value = route.query.dataId;
  getCollegeDetailsFn();
  campusIsCollectFn();
  getZtjUserInfoFn();
});

onActivated(() => {
  currentCollegeId.value = route.query.dataId;
  getCollegeDetailsFn();
  campusIsCollectFn();
  getCollegeFilterFn(); // 重新获取用户信息并执行后续流程
  activeTabIndex.value = 0;
});

onDeactivated(() => {
  // 组件被停用时执行的代码
});
</script>

<style lang="scss" scoped>
.search-college {
  background: linear-gradient(180deg, #e8f9ff 0%, #f4f6f8 100%);
  padding: 0 60px;
  box-sizing: border-box;
  .icon {
    width: 24px;
    height: 24px;
  }
  .header {
    padding: 30px 0px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .back-arrow {
      width: 48px;
      height: 48px;
      position: absolute;
      left: 0px;
    }
  }
  .school-info {
    width: 100%;
    .top {
      display: flex;
      gap: 13px;
      .left {
        .school-logo {
          width: 93px;
          height: 93px;
          border-radius: 50%;
        }
      }
      .right {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        gap: 6px;
        .school-name {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 36px;
          color: #333333;
          display: flex;
          align-items: center;
          .name {
            margin-right: 24px;
          }
          .label {
            background: #c7e6ff;
            border-radius: 5px;
            padding: 0 6px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 19px;
            color: #3386fe;
            height: 27px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 6px;
            box-sizing: border-box;
          }
        }
        .tags {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 22px;
          color: #666666;
        }
      }
      .star-box {
        display: flex;
        justify-content: center;
        padding: 10px;
        .star {
          width: 36px;
          height: 36px;
        }
      }
    }
    .middle {
      width: 100%;
      padding: 29px 51px;
      background: #ffffff;
      border-radius: 28px;
      box-sizing: border-box;
      margin-top: 28px;
      display: flex;
      .left {
        width: 50%;
        display: flex;
        align-items: center;
        gap: 100px;
        .left-item {
          display: flex;
          gap: 26px;
          align-items: center;
          .logo {
            img {
              width: 52px;
              height: 52px;
            }
          }
          .info {
            height: 66px;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            font-size: 22px;

            .title {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              color: #999999;
            }
          }
        }
      }
      .right {
        width: 50%;
        display: flex;
        flex-wrap: wrap;
        font-size: 22px;
        gap: 12px;
        .right-item {
          width: 48%;
          display: flex;
          align-items: center;
          gap: 9px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          img {
            width: 26px;
            height: 26px;
          }
          .site {
            color: #0b6eff;
          }
        }
      }
    }
    .main {
      .filter-box {
        margin-top: 37px;
        display: flex;
        padding-left: 22px;
        .active-tab {
          background: #0b6eff;
          border-radius: 18px 18px 0px 0px;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 24px;
          color: #ffffff;
          padding: 10px 83px;
        }
        .tab {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 24px;
          color: #000000;
          padding: 10px 83px;
        }
      }
      .container {
        width: 100%;
        height: calc(100vh - 472px);
        background: #ffffff;
        border-radius: 32px 32px 0px 0px;
        overflow: auto;
      }
    }
  }
}
</style>
